package com.example.communist_app_api.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.communist_app_api.db.dao.RoleDao;
import com.example.communist_app_api.db.dao.UserDao;
import com.example.communist_app_api.db.dao.UserRoleDao;
import com.example.communist_app_api.db.dto.UserDTO;
import com.example.communist_app_api.db.pojoDto.User;
import com.example.communist_app_api.exception.GlobalException;
import com.example.communist_app_api.service.UserService;
import com.example.communist_app_api.util.R;
import com.example.communist_app_api.util.StringUtil;
import com.example.communist_app_api.vo.uniapp.req.UniAppLoginReq;
import com.example.communist_app_api.vo.web.req.AuditPersonalMessageShowReq;
import com.example.communist_app_api.vo.web.req.UserSelectReq;
import com.example.communist_app_api.vo.web.req.UserUpdateMessageReq;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author love~mlm
 * @version 1.0
 * Create by 2022/11/19 12:22
 */
@Transactional
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    private RoleDao roleDao;

    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    public static final String STORAGE_PHOTO = "https://image-1314027391.cos.ap-guangzhou.myqcloud.com/20230218132558.png";

    public static final String ROLE_NAME = "游客";

    public User getUserInfo(String username){
        return userDao.getUserByUserName(username);
    }

    @Override
    public void editPersonMessage(User user) {
        userDao.editPersonMessage(user);
    }

    @Override
    public User getUserByUserId(Integer id) {
        return userDao.getUserByUserId(id);
    }


    //分页查询用户
    @Override
    public PageInfo<UserDTO> findPage(UserSelectReq req) {
        Integer pageNum = req.getPageNum();
        Integer pageSize = req.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        //创建UserDTO
        List<UserDTO> userDTOList = new ArrayList<>();
        //判断是否带条件查询，如果带条件查询就执行条件查询，否则就进行查询全部用户
        if (req.getUserName() != null && req.getUserName() != " ") {
            //没有进行模糊查找,携带组织id
            //User userByUserName = userDao.getUserByUserNameAndOrganizationId(req.getUserName(),req.getOrganizationId());
            //测试：
            User userByUserName = userDao.getUserByUserNameAndOrganizationId(req.getUserName(),1);


            UserDTO userDTO = new UserDTO();
            userDTO.setId(userByUserName.getId());
            userDTO.setPhoto(userByUserName.getPhoto());
            userDTO.setEmail(userByUserName.getEmail());
            userDTO.setName(userByUserName.getName());
            userDTO.setTelephone(userByUserName.getTelephone());
            userDTO.setUpdatedTime(userByUserName.getUpdatedTime());
            userDTO.setHiredate(userByUserName.getHiredate());
            if (userByUserName.getSex() == 0) {
                userDTO.setSex("男");
            }else {
                userDTO.setSex("女");
            }
            userDTO.setStatus(userByUserName.getStatus());
            userDTOList.add(userDTO);
        }else {
            //查询用户
            //List<User> userList = userDao.getAllUser(req.getOrganizationId());
            //测试：
            List<User> userList = userDao.getAllUser(1);
            for (User user :userList) {
                Date hiredate = user.getHiredate();
                //判断是否进入党支部
                if (hiredate != null&&(user.getStatus() == 1 ||user.getStatus() == 0) ) {
                    UserDTO userDTO = new UserDTO();
                    userDTO.setId(user.getId());
                    userDTO.setPhoto(user.getPhoto());
                    userDTO.setEmail(user.getEmail());
                    userDTO.setName(user.getName());
                    userDTO.setTelephone(user.getTelephone());
                    userDTO.setUpdatedTime(user.getUpdatedTime());
                    userDTO.setStatus(user.getStatus());
                    userDTO.setHiredate(user.getHiredate());
                    if (user.getSex() == 0) {
                        userDTO.setSex("男");
                    }else {
                        userDTO.setSex("女");
                    }
                    userDTOList.add(userDTO);
                }
            }
        }

        if (userDTOList.size() == 0) {
            R.error("查询失败");
        }
        return new PageInfo<UserDTO>(userDTOList,5);
    }
    //分页查询没有被审批的用户
    @Override
    public PageInfo<User> findPageByAudit(AuditPersonalMessageShowReq req) {
        PageHelper.startPage(req.getPageNum(),req.getPageSize());

        //测试：
        //List<User> userList = userDao.getAllAuditUser(req.getPhone(),1);
        List<User> userList = userDao.getAllAuditUser(req.getPhone(),req.getOrganizationId());

        return new PageInfo<>(userList,5);
    }

    @Override
    public Boolean updateUserMessage(UserUpdateMessageReq req) {
        User user = userDao.getUserByUserId(req.getUserId());
        //设置状态
        user.setStatus(req.getStatus());
        //邮箱地址、用户姓名、电话号码、状态
        user.setEmail(req.getEmail());
        user.setName(req.getName());
        user.setTelephone(req.getTelephone());
        Boolean flag = userDao.updateUserMessage(user);
        if (flag == true) {
            return true;
        }else {
            return false;
        }

    }

    @Override
    public void deleteUserMessage(Integer userId) {
        userDao.deleteUserMessage(userId);
    }

    @Override
    public int getUserByUserName(String name) {
        int num = userDao.getUserNumByUserName(name);
        return num;
    }

    //获取所有党支部成员名字
    @Override
    public List<User> getAllCommunistMember(Integer organizationId) {
        List<User> userBriefInfo = userDao.getAllUserBriefInfo(organizationId);
        if (userBriefInfo == null) {
            throw new GlobalException("查询结果为空",500);

        }

        List<User> userList = userBriefInfo.stream().filter(user -> user.getHiredate() != null)
                .collect(Collectors.toList());

        return userList;
    }

    @Override
    public int login(UniAppLoginReq req) {
        String openId = getOpenId(req.getCode());
        //通过openId在数据库中寻找，获取主键Id的过程
        Integer id = userDao.searchIdByOpenId(openId);
        if (id == null) {
            //如果id为空就注册用户
            User user = new User();
            user.setOpenId(openId);
            //统一修改成为1，在小程序端
            user.setStatus((byte) 1);
            //默认密码
            user.setPassword("123456");
            //设置统一的图片
            user.setPhoto(STORAGE_PHOTO);
            //设置初始username为openId
            user.setName(openId);
            try {
                userDao.insertUser(user);
            } catch (Exception e) {
                throw new GlobalException("注册异常");
            }
            //上述无异常情况下，需要添加user_role表初始化游客身份
            Integer roleId = roleDao.getRoleByRoleName(ROLE_NAME).getId();
            userRoleDao.assignRole(user.getId(), roleId);
            return user.getId();
        }
        return id;
    }

    @Override
    public User getUserBriefInfoByUserId(Integer id) {
        User user = userDao.getUserBriefInfoByUserId(id);
        String nameDesensitization = StringUtil.nameDesensitization(user.getName());
        user.setName(nameDesensitization);
        return user;
    }

    //通过code 换取 openId
    private String getOpenId(String code){
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        HashMap map=new HashMap();
        map.put("appid", appId);
        map.put("secret", appSecret);
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String response= HttpUtil.post(url,map);
        JSONObject json= JSONUtil.parseObj(response);
        String openId=json.getStr("openid");
        if(openId==null||openId.length()==0){
            throw new RuntimeException("临时登陆凭证错误");
        }
        return openId;
    }

    @Override
    public User getNamePhoto(Integer userId) {
        return userDao.getNamePhoto(userId);
    }
}
